package pres.lnk.learn.designpattern.c_singleton;

/**
 * 单例模式
 * 懒汉式一（懒加载），线程不安全
 * @Author lnk
 * @Date 2018/2/1
 */
public class Singleton2 {
    private static Singleton2 instance;
    private int i;

    /**
     * 私有化构造函数，防止被构建新的对象
     */
    private Singleton2(){

    }

    /**
     * 获取唯一实例，当用到时再加载对象
     * @return
     */
    public static Singleton2 getInstance(){
        if(instance == null){
            try {
                //模拟线程不安全
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            instance = new Singleton2();
        }
        return instance;
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(){
            @Override
            public void run() {
                Singleton2 s = Singleton2.getInstance();
                s.setI(5);
                System.out.println("setI " + s.getI());
            }
        };
        Thread t2 = new Thread(){
            @Override
            public void run() {
                Singleton2 s = Singleton2.getInstance();
                //预期结果应该是5的
                System.out.println("getI " + s.getI());
            }
        };

        t1.start();
        try {
            //确保t1先跑起来
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t2.start();
    }

    public int getI() {
        return i;
    }

    public void setI(int i) {
        this.i = i;
    }
}
